package org.jetnuke.blocks;

import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IBlock;
import org.jetnuke.common.IBlockInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BannerDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.Banner;



public class Advertising implements IBlock {

	/* (non-Javadoc)
	 * @see org.jetnuke.common.IBlock#serviceBlock(javax.servlet.http.HttpServletRequest, org.apache.velocity.VelocityContext, org.jetnuke.common.IBlockInfo, org.jetnuke.common.IUserInfo, org.jetnuke.common.IAdminInfo)
	 */
	public void serviceBlock(HttpServletRequest req, VelocityContext vc,
			IBlockInfo blockInfo, IUserInfo userInfo, IAdminInfo adminInfo)
			throws Exception {
		int bannum=0;
		BannerDAO bm=DataAccessDriver.getInst().newJBannerDAO();
		int numrows=bm.countActiveByType(1);
		//int numrows=bannerPeer.count(new Criteria().add(bannerPeer.TYPE,1).add(bannerPeer.ACTIVE,1));
		if(numrows>1){
			bannum=new Random().nextInt(numrows);
		}
		if(numrows>0){
			List ls=bm.selectActiveByTypeOffset(1,bannum);
				//bannerPeer.doSelect(new Criteria().add(bannerPeer.TYPE,1).add(bannerPeer.ACTIVE,1).setOffset(bannum).setLimit(1));
			if(ls.size()>0){
				Banner bn=(Banner)ls.get(0);
				if(adminInfo!=null){//Update clicks only for non admin
					bn.setIMPMADE(bn.getIMPMADE()+1);
					//bn.save();
					bm.update(bn);
				}
				if(bn.getIMPTOTAL()>0 && bn.getIMPTOTAL()>bn.getIMPMADE()){
					bn.setACTIVE(0);
					//bn.save();
					bm.update(bn);
				}
				vc.put("banner",bn);
			}
		}
	}

}
